package routinePractice

import (
	"fmt"
	"sync"
	"time"
)

/*
原理 并发资源 abcdef 没有共享资源 并发完成后 回主线程
*/
func shout() {
	v := 0
	for index := 0; index < 5000000; index++ {
		v += index
		//time.Sleep(time.Millisecond * 1)
	}

}

func LockTest(name string) {
	fmt.Println(name)
	shout()
}

func Process(input string) {
	fmt.Printf("并发用时%v , 正常用时%v \n", routineMode(input), modeNormal(input))

}

func routineMode(input string) time.Duration {
	wg := sync.WaitGroup{}
	data := generatorChan(input)

	//计数器+
	m1 := time.Now()
	wg.Add(len(input))

	for d, ok := <-data; ok; {
		go func() { LockTest(string(d)); wg.Done() }()
		d, ok = <-data
	}

	wg.Wait()

	return time.Since(m1)
}

func modeNormal(input string) time.Duration {

	m2 := time.Now()

	for i := 0; i < len(input); i++ {
		LockTest(string(input[i]))
	}
	return time.Since(m2)
}

func generatorChan(input string) (data chan byte) {
	data = make(chan byte, len(input))
	for i := 0; i < len(input); i++ {
		data <- input[i]
	}
	close(data)
	return
}
